import * as XLSX from 'xlsx'

export async function try_get_sheet(file:File){
    const work_book=XLSX.read(await file.arrayBuffer(),{type:'array',raw:true})

    try {
        return work_book.Sheets[work_book.SheetNames[0]]
    } catch (error) {
        throw '读取工作表失败!'
    }
}

export function read_cell(sheet:any,row_idx:number,col_idx:string|undefined) {
    if (!col_idx) {
        return ''
    }
    col_idx=col_idx.toUpperCase()
    try {
        const cell_pos=col_idx+row_idx
        const value= sheet[col_idx+row_idx]
        if (typeof value == 'string' || typeof value=='number') {
            return ''+value
        }else{
            return ''+value['v']
        }
    } catch (error) {
        return ''
    }
}

export function has_row(sheet:any,row_idx:number){
    return 'A'+row_idx in sheet
}

export function try_parse_positive_number(name:string,value:string,row_idx:number){
    if (value=='') {
        throw `读取${name}失败, 行号[${row_idx}]`
    }
    const count=+value
    if (Number.isInteger(count)==false) {
        throw `${name}[${value}]不是一个有效整数, 行号[${row_idx}]`
    }
    if (count<0) {
        throw `${name}[${count}]不能为负数, 行号[${row_idx}]`
    }
    return count
}